package com.imooc.mall.service;

import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.dao.UserMapper;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User getUser() {
        User user = userMapper.selectByPrimaryKey(1);
        return user;
    }

    @Override
    public void register(String username, String password) throws ImoocMallException {
        //查询用户名是否存在,不许重名
        User result = userMapper.selectByUsername(username);
        if (result != null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTED);
        }
        //写入到数据看
        User user = new User();
        user.setUsername(username);
        //对用户的密码进行加密
        try {
            String md5String = MD5Utils.getMD5String(password);
            user.setPassword(md5String);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        int count = userMapper.insertSelective(user);
        if (count == 0) {
            throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String username, String password) throws ImoocMallException {
        String md5Password = null;
        try {
            md5Password = MD5Utils.getMD5String(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userMapper.selectLogin(username,  md5Password);

        if (user == null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.LOGIN_FAILED);
        }
        return user;

    }

    @Override
    public void updateInformation(User user) throws ImoocMallException {
        int count = userMapper.updateByPrimaryKeySelective(user);
        if(count>1){
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean checkAdminRole(User user){
        //1.是普通用户 2是管理员
       return user.getRole().equals(2);
    }

}
